package com.sq.system.controller;

import com.sq.api.dto.SysUserDto;
import com.sq.api.user.model.LoginUser;
import com.sq.common.ana.Log;
import com.sq.common.utils.StringUtils;
import com.sq.common.web.R;
import com.sq.common.web.base.TableDataInfo;
import com.sq.common.web.domain.AjaxResult;
import com.sq.system.base.BaseController;
import com.sq.system.pojo.SysDept;
import com.sq.system.pojo.SysRole;
import com.sq.system.pojo.SysUser;
import com.sq.system.service.ISysDeptService;
import com.sq.system.service.SysMenuService;
import com.sq.system.service.SysRoleService;
import com.sq.system.service.SysUserService;
import com.sq.system.utils.RoleUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author Li sir
 * @Date 2024/9/29
 */

@RestController
@RequestMapping("/api/user/")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private ISysDeptService deptService;

    @GetMapping("info/{username}")
    public R<LoginUser> userInfo(@PathVariable("username") String userName){

        // 1.查询用户信息
        SysUser sysUser = sysUserService.userinfo(userName);

        if (Objects.isNull(sysUser)){
            return R.fail("用户名错误");
        }

        // 2.查询用户角色信息
        List<SysRole> sysRoles = sysRoleService.selectRoleByUserId(sysUser.getUserId());

        // 3. 查询用户权限信息
        Set<String> rolePermissions = sysMenuService.selectRolePermissions(sysRoles);

        // 角色list变化
        Set<String> userRoleIds = RoleUtil.getUserRoleIds(sysRoles);
        Set<String> userRoleStrs = RoleUtil.getUserRoleStrs(sysRoles);
        LoginUser loginUser = new LoginUser();

        loginUser.setUserid(sysUser.getUserId());
        loginUser.setUsername(sysUser.getLoginName());
        loginUser.setRoleIds(userRoleIds);
        loginUser.setRoleNames(userRoleStrs);
        loginUser.setPermissions(rolePermissions);
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(sysUser,sysUserDto);
        loginUser.setSysUser(sysUserDto);
        // 4. 结果返回
        return R.ok(loginUser);
    }


    @PostMapping("saveuser")
    @Log(title = "用户管理",businessType = "新增用户")
    public R<Integer> saveUser(@RequestBody SysUserDto sysUserDto){
        int i = sysUserService.saveSysUser(sysUserDto);
        return R.ok(i);
    }

    @GetMapping("exist/{username}")
    public R<LoginUser> checkUserExist(@PathVariable("username") String userName){

        // 1.查询用户信息
        SysUser sysUser = sysUserService.userinfo(userName);

        if (Objects.isNull(sysUser)){
            return  R.fail();
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(sysUser.getUserId());
        loginUser.setUsername(sysUser.getLoginName());
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(sysUser,sysUserDto);
        loginUser.setSysUser(sysUserDto);
        return R.ok(loginUser);
    }


    @PostMapping("list")
    public TableDataInfo list(@RequestBody SysUser sysUser){
        startPage(sysUser.getPageNum(),sysUser.getPageSize());
        List<SysUser> list = sysUserService.selectVo(sysUser);
        return getDataTable(list);
    }

    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
//        sysUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = sysRoleService.selectRoleWhere(new SysRole());
        ajax.put("roles", roles );
        if (StringUtils.isNotNull(userId))
        {
            // 获取到用户
            SysUser sysUser = sysUserService.getById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            // 获取到用户对应的角色
            List<SysRole> sysRoles = sysRoleService.selectRoleByUserId(String.valueOf(userId));
            ajax.put("roleIds", sysRoles.stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    @DeleteMapping("del/{userId}")
    public AjaxResult delUser(@PathVariable("userId") String userId){
        boolean off = sysUserService.deleteUserById(userId);
        if (off){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @PostMapping("update")
    public AjaxResult updateUser(@RequestBody SysUserDto sysUserDto){
        boolean off = sysUserService.updateUser(sysUserDto);
        if (off){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

}
